package com.hcb.tonguetiphealth.manager;

import java.io.IOException;
import java.text.SimpleDateFormat;

import org.json.JSONException;
import org.json.JSONObject;

import android.R.bool;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.widget.GeneralWidget;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.net.RequestListener;

public class WeiboManager extends GeneralWidget {

	private Weibo mWeibo;
    private static final String CONSUMER_KEY = "3563976353";// 替换为开发者的appkey，例如"1646212860";
    private static final String REDIRECT_URL = "http://www.sina.com";//与应用写的回调地址需一致
    public static Oauth2AccessToken accessToken;
    public static final String TAG = "sinasdk";
    private String shareContent = "";
    private String allAddContnt = " //@舌尖健康:http://www.5xle.com.cn/   健康你我他，关注他，就是关心他! ";
    private Activity ctx;
    private Context context;
    private Handler mHandler;
    private String shareCOntentPic;
    private boolean shareSucess = false;
    
    public WeiboManager(Context contex){
    	super(contex);
		ctx = (Activity)contex;
		this.context = contex;
		shareContent = allAddContnt;
		mHandler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case MessageWhat.WEIBO_AUTH_SUCESS:
					showMessageDialog(ctx, "正在发布微博...");
					if (shareCOntentPic !=null && shareCOntentPic.length()>0) {
						shareContentPic();
					}else {
						shareContent();
					}
					break;
				case MessageWhat.WEIBO_AUTH_FAIL:
					
					break;
				case MessageWhat.WEIBO_UPDATE_SUCESS:
					dismissMessageDialog();
					Toast.makeText(ctx, "分享成功！", Toast.LENGTH_LONG).show();
					shareSucess = true;
					break;
				case MessageWhat.WEIBO_UPDATE_FAIL:
					dismissMessageDialog();
					String erroMsg = (String)msg.obj;
					Toast.makeText(ctx, "分享失败:"+erroMsg, Toast.LENGTH_LONG).show();
					shareSucess = false;
					break;
				default:
					break;
				}
			}
			
		};
	}
    
    public void authWeibo(){
    	mWeibo = Weibo.getInstance(CONSUMER_KEY, REDIRECT_URL);
		mWeibo.authorize(context, new AuthDialogListener());
    }
    
    private void shareContentPic(){
    	 StatusesAPI api = new StatusesAPI(accessToken);
    	 api.upload(shareContent,shareCOntentPic, "", "", new RequestListener() {
 			
 			@Override
 			public void onIOException(IOException arg0) {
 				// TODO Auto-generated method stub
 				mHandler.sendEmptyMessage(MessageWhat.WEIBO_UPDATE_FAIL);
 			}
 			
 			@Override
 			public void onError(WeiboException arg0) {
 				// TODO Auto-generated method stub
 				String errorMsg = ""; 
 				System.out.println("错误："+arg0.getMessage());
 				//message: {"error":"repeat content!","error_code":20019,"request":"/2/statuses/update.json"}-----------
 				//解析错误信息，显示错误原因
 				try {
					JSONObject jsonObject = new JSONObject(arg0.getMessage());
					String erroeCode  = jsonObject.getString("error_code");
					if ("20019".equals(erroeCode)) {
						errorMsg = "不能发布相同的微博哦~";
					}
					if ("20012".equals(erroeCode) || "20013".equals(erroeCode)) {
						errorMsg = "您输入的文字太长啦！140字以内~";
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Message message = new Message();
 				message.what = MessageWhat.WEIBO_UPDATE_FAIL;
				message.obj = errorMsg;
 				mHandler.sendMessage(message);
 			}
 			
 			@Override
 			public void onComplete(String arg0) {
 				// TODO Auto-generated method stub
 				mHandler.sendEmptyMessage(MessageWhat.WEIBO_UPDATE_SUCESS);
 			}
 		});
    }
    
    private void shareContent(){
   	 StatusesAPI api = new StatusesAPI(accessToken);
   	api.update(shareContent,"","", new RequestListener() {
			
			@Override
			public void onIOException(IOException arg0) {
				// TODO Auto-generated method stub
				mHandler.sendEmptyMessage(MessageWhat.WEIBO_UPDATE_FAIL);
			}
			
			@Override
			public void onError(WeiboException arg0) {
				// TODO Auto-generated method stub
				String errorMsg = ""; 
				System.out.println("错误："+arg0.getMessage());
				//message: {"error":"repeat content!","error_code":20019,"request":"/2/statuses/update.json"}-----------
				//解析错误信息，显示错误原因
				try {
					JSONObject jsonObject = new JSONObject(arg0.getMessage());
					String erroeCode  = jsonObject.getString("error_code");
					if ("20019".equals(erroeCode)) {
						errorMsg = "不能发布相同的微博哦~";
					}
					if ("20012".equals(erroeCode) || "20013".equals(erroeCode)) {
						errorMsg = "您输入的文字太长啦！140字以内~";
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Message message = new Message();
				message.what = MessageWhat.WEIBO_UPDATE_FAIL;
				message.obj = errorMsg;
				mHandler.sendMessage(message);
			}
			
			@Override
			public void onComplete(String arg0) {
				// TODO Auto-generated method stub
				mHandler.sendEmptyMessage(MessageWhat.WEIBO_UPDATE_SUCESS);
			}
		});
   }

    class AuthDialogListener implements WeiboAuthListener {

        @Override
        public void onComplete(Bundle values) {
            String token = values.getString("access_token");
            String expires_in = values.getString("expires_in");
            accessToken = new Oauth2AccessToken(token, expires_in);
            if (accessToken.isSessionValid()) {
                String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
                        .format(new java.util.Date(accessToken
                                .getExpiresTime()));
                System.out.println("认证成功！--"+"认证成功: \r\n access_token: " + token + "\r\n"
                        + "expires_in: " + expires_in + "\r\n有效期：" + date);
                StatusesAPI api = new StatusesAPI(accessToken);
                mHandler.sendEmptyMessage(MessageWhat.WEIBO_AUTH_SUCESS);
//                api.update(shareContent,"","", new RequestListener() {
//        			
//        			@Override
//        			public void onIOException(IOException arg0) {
//        				// TODO Auto-generated method stub
//        				
//        			}
//        			
//        			@Override
//        			public void onError(WeiboException arg0) {
//        				// TODO Auto-generated method stub
//        				
//        			}
//        			
//        			@Override
//        			public void onComplete(String arg0) {
//        				// TODO Auto-generated method stub
//        				System.out.println("suncess1111111111");
//        			}
//        		});
//                api.upload(shareContent+"tupian","/sdcard/DCIM/Camera/IMG_20130226_002413.jpg", "", "", new RequestListener() {
//					
//					@Override
//					public void onIOException(IOException arg0) {
//						// TODO Auto-generated method stub
//						
//					}
//					
//					@Override
//					public void onError(WeiboException arg0) {
//						// TODO Auto-generated method stub
//						
//					}
//					
//					@Override
//					public void onComplete(String arg0) {
//						// TODO Auto-generated method stub
//						System.out.println("suncess22222222222222222222");
//					}
//				});
            }
        }

        @Override
        public void onError(WeiboDialogError e) {
            Toast.makeText(ctx,
                    "Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(ctx, "Auth cancel",
                    Toast.LENGTH_LONG).show();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(ctx,
                    "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }
    }

	@Override
	public void notifyAdapter() {
		// TODO Auto-generated method stub
		
	}

	public boolean isShareSucess() {
		return shareSucess;
	}

	public void setShareSucess(boolean shareSucess) {
		this.shareSucess = shareSucess;
	}

	public String getShareContent() {
		return shareContent;
	}

	public void setShareContent(String shareContent) {
		this.shareContent = shareContent + allAddContnt;
	}

	public String getShareCOntentPic() {
		return shareCOntentPic;
	}

	public void setShareCOntentPic(String shareCOntentPic) {
		this.shareCOntentPic = shareCOntentPic;
	}
	
}
